//
//  MyController.m
//  HandheldHospital
//
//  Created by zhangchao on 16/2/25.
//  Copyright © 2016年 zhangchao. All rights reserved.
//

#import "MyController.h"
#import "DataManager.h"
#import "LoginViewController.h"
#import "SettingsViewController.h"
#import "CollectingDoctorViewController.h"
#import "CollectingHospitalViewController.h"
#import "MedicalRecordViewController.h"
#import "MyDoctorViewController.h"
#import "MyManagerViewController.h"
#import "RegistrationListViewController.h"
#import "MyPatientViewController.h"
#import <ZBarSDK/ZBarSDK.h>
#import <Masonry/Masonry.h>
#import "DataManager.h"




#define kWidth self.view.frame.size.width
#define kHeight self.view.frame.size.height
#define kShared [DataManager defaultManager]

@interface MyController ()<UIImagePickerControllerDelegate,ZBarReaderDelegate>
{
    int num;
    BOOL upOrdown;
    NSTimer * timer;
}
@property (nonatomic,strong) UIImageView *imageV;
@property (nonatomic, strong) UIImageView * line;
@property (nonatomic,strong) NSArray *array;
@property (nonatomic,strong) NSArray *arr;
@property (nonatomic,strong) NSArray *doctorArray;
@property (nonatomic,strong) NSArray *doctorArr;
@property (nonatomic,strong) NSString *state;
@property (nonatomic,strong) AVUser *myUser;
@property (nonatomic,strong) NSArray *doctorImageArray;
@property (nonatomic,strong) NSArray *imageArray;
@end

@implementation MyController

//医生的图标数组
- (NSArray *)doctorImageArray
{
    if(_doctorImageArray == nil)
    {
        _doctorImageArray = [NSArray arrayWithObjects:@[@"wodeziliao",@"huanzhe"],@[@"dianzibingli"],@[@"shezhi"], nil];
    }
    return _doctorImageArray;
}

- (NSArray *)imageArray
{
    if(_imageArray == nil)
    {
        _imageArray = [NSArray arrayWithObjects:@[@"yiyuan",@"yisheng",@"order-manager"],@[@"saoyisao"],@[@"guahao",@"dianzibingli"],@[@"shezhi"], nil];
    }
    return _imageArray;
}


//懒加载
- (NSArray *)array
{
    if(_array == nil)
    {
        _array = @[@[@"收藏的医院",@"我的医生",@"就诊人管理"],@[@"扫一扫"],@[@"挂号订单",@"电子病历"],@[@"设置"]];
    }
    return _array;
}

//懒加载
- (NSArray *)doctorArray
{
    if(_doctorArray == nil)
    {
        _doctorArray = @[@[@"我的资料",@"我的患者"],@[@"电子病历"],@[@"设置"]];
    }
    return _doctorArray;
}


//懒加载
- (NSArray *)arr
{
    if(_arr == nil)
    {
        _arr = [NSArray arrayWithObjects:@"收藏的医院",@"我的医生",@"就诊人管理",@"扫一扫",@"挂号订单",@"电子病历",@"设置",nil];
        
    }
    return _arr;
}

- (NSArray *)doctorArr
{
    if(_doctorArr == nil)
    {
        _doctorArr = [NSArray arrayWithObjects:@"我的资料",@"我的患者",@"电子病历",@"设置", nil];
    }
    return _doctorArr;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    
    if(kShared.myUser == nil)
    {
        self.navigationItem.rightBarButtonItem.title = @"登录";

    }else
    {
        self.navigationItem.rightBarButtonItem.title = @"注消";
    }
    //判断是不是医生
    if([kShared.userType isEqualToString:@"医生"])
    {
        //如果没有医生信息，或者不是当前是医生用户的信息,就从数据库中获取
        if(kShared.seek == nil || kShared.seek.currentUser != [AVUser currentUser])
        {
            [kShared getSeekModel];
        }
    }

    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    if(kShared.myUser == nil)
    {
        self.state = @"登录";
        
    }else 
    {
        self.state = @"注消";
    }
    self.navigationItem.title = @"我的";
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:self.state style:UIBarButtonItemStyleDone target:self action:@selector(didClickRight:)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//右边按钮点击事件
- (void)didClickRight:(UIBarButtonItem *)sender
{
    //判断当前登录状态,来显示右按钮是登录还是注消
    if(kShared.myUser == nil)
    {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES  ];
    }
    else
    {
        [self clearkShared];
        self.navigationItem.rightBarButtonItem.title = @"登录";
    }
}


//清空单例数据
- (void)clearkShared
{
    //清除当前用户
    kShared.myUser = nil;
    //清除用户类型
    kShared.userType = nil;
    //清除就诊人数组
    [kShared.dataArray removeAllObjects];
    //清除患者数组
    [kShared.managerArray removeAllObjects];
    //清除病历数组
    [kShared.medicalArray removeAllObjects];
    //清除挂号订单数组
    [kShared.registerArray removeAllObjects];
    //清除我的医生数组
    [kShared.collectDoctorArray removeAllObjects];
    //清除收藏的医院数组
    [kShared.collectHospitalArray removeAllObjects];
}


#pragma mark - Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    //判断用户类型
    if([kShared.userType isEqualToString:@"医生"])
    {
        return self.doctorArray.count;
    }
    return self.array.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //判断用户类型
    if([kShared.userType isEqualToString:@"医生"])
    {
        NSArray *a = [NSArray arrayWithArray:self.doctorArray[section]];
        return a.count;
    }
    NSArray *a = [NSArray arrayWithArray:self.array[section]];
    return a.count;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if([kShared.userType isEqualToString:@"医生"])
    {
        cell.imageView.image = [UIImage imageNamed:self.doctorImageArray[indexPath.section][indexPath.row]];
        cell.textLabel.text = self.doctorArray[indexPath.section][indexPath.row];
    }
    else
    {
        cell.imageView.image = [UIImage imageNamed:self.imageArray[indexPath.section][indexPath.row]];
        cell.textLabel.text = self.array[indexPath.section][indexPath.row];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //判断当前登录状态，如果未登录，跳到登录页面
    if(kShared.myUser == nil)
    {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES  ];
    }   //如果已经登录了，通过判断点击的下标来跳转到相应页面
    else 
    {
        if([kShared.userType isEqualToString:@"医生"])
        {
            //获取点击的下标
            NSString *str = self.doctorArray[indexPath.section][indexPath.row];
            NSInteger index = [self.doctorArr indexOfObject:str];
            [self pushViewControllerByIndex:index];
        }
        else
        {
            //获取点击的下标
            NSString *str = self.array[indexPath.section][indexPath.row];
            NSInteger index = [self.arr indexOfObject:str];
            [self pushViewControllerByIndex:index];
        }
    }
}

//通过点击的cell的下标来跳转到指定页面
- (void)pushViewControllerByIndex:(NSInteger)index
{
    //判断用户类型
    if([kShared.userType isEqualToString:@"医生"])
    {
        switch (index) {
            case 0: //跳转到我的资料
            {
                MyDoctorViewController *myDoctorVC = [[MyDoctorViewController alloc] init];
                [self.navigationController pushViewController:myDoctorVC animated:YES];
            }break;
            case 1: //跳转到我的患者
            {
                MyPatientViewController *myPatientVC = [[MyPatientViewController alloc] init];
                [self.navigationController pushViewController:myPatientVC animated:YES];
            }break;
            case 2: //跳转到电子病历
            {
                MedicalRecordViewController *medicalRecordVC = [[MedicalRecordViewController alloc] init];
                [self.navigationController pushViewController:medicalRecordVC animated:YES];
            }break;
            case 3: //跳转到设置页
            {
                SettingsViewController *settingsVC = [[SettingsViewController alloc] init];
                [self.navigationController pushViewController:settingsVC animated:YES];
            }break;
        }
    }
    else
    {
        switch (index) {
            case 0: //跳转到收藏的医院
            {
                CollectingHospitalViewController *collectingHospitalVC = [[CollectingHospitalViewController alloc] init];
                self.tabBarController.tabBar.hidden = YES;
                [self.navigationController pushViewController:collectingHospitalVC animated:YES];
                
            }break;
            case 1: //跳转到我的医生
            {
                CollectingDoctorViewController *collectingDoctorVC = [[CollectingDoctorViewController alloc] init];
                [self.navigationController pushViewController:collectingDoctorVC animated:YES];
            }break;
            case 2: //跳转到就诊人管理
            {
                MyManagerViewController *myManagerVC = [[MyManagerViewController alloc] init];
                [self.navigationController pushViewController:myManagerVC animated:YES];
            }break;
            case 3: //扫一扫
            {
                [self scanBtnAction];
                
            }break;
            case 4: //跳转到挂号订单
            {
                RegistrationListViewController *registrationListVC = [[RegistrationListViewController alloc] init];
                [self.navigationController pushViewController:registrationListVC animated:YES];
            }break;
            case 5: //跳转到电子病历
            {
                MedicalRecordViewController *medicalRecordVC = [[MedicalRecordViewController alloc] init];
                [self.navigationController pushViewController:medicalRecordVC animated:YES];
            }break;
            case 6: //跳转到设置
            {
                SettingsViewController *settingsVC = [[SettingsViewController alloc] init];
                [self.navigationController pushViewController:settingsVC animated:YES];
            }break;
        }
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}


#pragma mark 扫一扫实现
-(void)scanBtnAction
{
    num = 0;
    upOrdown = NO;
    //初始话ZBar
    ZBarReaderViewController * reader = [ZBarReaderViewController new];
    //设置代理
    reader.readerDelegate = self;
    //支持界面旋转
    reader.supportedOrientationsMask = ZBarOrientationMaskAll;
    reader.showsHelpOnFail = NO;
    
    reader.scanCrop = CGRectMake(0.3, 0.05, 0.8, 0.8);//扫描的感应框
    
    ZBarImageScanner * scanner = reader.scanner;
    [scanner setSymbology:ZBAR_I25
                   config:ZBAR_CFG_ENABLE
                       to:0];
    UIView * addview = [[UIView alloc] initWithFrame:self.view.bounds];
    addview.backgroundColor = [UIColor clearColor];
    reader.cameraOverlayView = addview;
    
    
    UILabel * label = [[UILabel alloc] init];
    label.text = @"请将扫描的二维码置于下面的框内\n谢谢！";
    label.textColor = [UIColor whiteColor];
    label.textAlignment = 1;
    label.lineBreakMode = 0;
    label.numberOfLines = 2;
    label.backgroundColor = [UIColor clearColor];
    [addview addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(addview).with.offset(kHeight * 0.2);
        make.left.equalTo(addview).with.offset(20);
        make.right.equalTo(addview).with.offset(-20);
        make.height.equalTo(@40);
    }];
    
    _imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pick_bg.png"]];
    [addview addSubview:_imageV];
    [_imageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(addview).with.offset(kHeight * 0.3);
        make.left.equalTo(addview).with.offset(kWidth * 0.05);
        make.right.equalTo(addview).with.offset(-(kWidth * 0.05));
        make.height.equalTo(@280);
    }];
    
    
    _line = [[UIImageView alloc] init];
    _line.image = [UIImage imageNamed:@"line.png"];
    [_imageV addSubview:_line];
    [_line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_imageV).with.offset(10);
        make.left.equalTo(_imageV).with.offset(20);
        make.right.equalTo(_imageV).with.offset(-20);
        make.height.equalTo(@2);
    }];
    //定时器，设定时间过1.5秒，
    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
    
    [self presentViewController:reader animated:YES completion:^{
        
    }];
}

-(void)animation1
{
    if (upOrdown == NO) {
        num ++;
        [_line mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_imageV).with.offset(10+2*num);
            make.left.equalTo(_imageV).with.offset(20);
            make.right.equalTo(_imageV).with.offset(-20);
            make.height.equalTo(@2);
        }];
        if (2*num == 260) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        [_line mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_imageV).with.offset(10+2*num);
            make.left.equalTo(_imageV).with.offset(20);
            make.right.equalTo(_imageV).with.offset(-20);
            make.height.equalTo(@2);
        }];
        if (num == 0) {
            upOrdown = NO;
        }
    }
    
    
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [timer invalidate];
    [_line mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_imageV).with.offset(10);
        make.left.equalTo(_imageV).with.offset(20);
        make.right.equalTo(_imageV).with.offset(-20);
        make.height.equalTo(@2);
    }];
    
    num = 0;
    upOrdown = NO;
    [picker dismissViewControllerAnimated:YES completion:^{
        [picker removeFromParentViewController];
        
    }];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [timer invalidate];
    [_line mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_imageV).with.offset(10);
        make.left.equalTo(_imageV).with.offset(20);
        make.right.equalTo(_imageV).with.offset(-20);
        make.height.equalTo(@2);
    }];
    num = 0;
    upOrdown = NO;
    [picker dismissViewControllerAnimated:YES completion:^{
        [picker removeFromParentViewController];
        UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
        //初始化
        ZBarReaderController * read = [ZBarReaderController new];
        //设置代理
        read.readerDelegate = self;
        CGImageRef cgImageRef = image.CGImage;
        ZBarSymbol * symbol = nil;
        id <NSFastEnumeration> results = [read scanImage:cgImageRef];
        for (symbol in results)
        {
            break;
        }
        NSString * result;
        if ([symbol.data canBeConvertedToEncoding:NSShiftJISStringEncoding])
            
        {
            result = [NSString stringWithCString:[symbol.data cStringUsingEncoding: NSShiftJISStringEncoding] encoding:NSUTF8StringEncoding];
        }
        else
        {
            result = symbol.data;
        }
        //判断扫到的是不是一个网址类型的
        if([result rangeOfString:@"http"].location != NSNotFound)
        {
            //如果是就打开这个网址
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:result]];
        }
        else
        {
            [self showAlertOneButtonWithTitle:@"抱歉" AndMessage:@"暂不支持此二维码" AndAlertStyle:UIAlertControllerStyleAlert AndOneButtonTitle:@"确定" AndBlock:nil];
        }
    }];
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
